<template>
  <div class="admin-product-page">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div class="admin-logo">
          <div class="admin-logo-icon">管</div>
          <div class="admin-logo-text">管理系统</div>
        </div>
      </div>
      
      <div class="sidebar-menu">
        <div 
          v-for="menu in menuList" 
          :key="menu.name"
          class="menu-item"
          :class="{ active: menu.name === 'product' }"
          @click="handleMenuClick(menu)"
        >
          <div class="menu-icon">{{ menu.icon }}</div>
          <span>{{ menu.label }}</span>
        </div>
      </div>
      
      <div class="sidebar-footer">
        <div class="admin-avatar-container">
          <div class="admin-avatar">{{ adminInitial }}</div>
          <div class="admin-info">
            <div class="admin-name">{{ adminName }}</div>
            <div class="admin-role">超级管理员</div>
          </div>
        </div>
        
        <!-- 退出登录按钮 -->
        <div class="logout-btn" @click="handleLogout">
          <div class="logout-icon">🚪</div>
          <span>退出登录</span>
        </div>
      </div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 顶部导航 -->
      <div class="top-nav">
        <h1 class="page-title">
          <div class="page-title-icon">🛒</div>
          商品与分类管理
        </h1>
        
        <div class="top-actions">
          <el-button 
            v-if="activeTab === 'product'" 
            class="action-btn primary-btn" 
            @click="handleAdd"
          >
            <span class="btn-icon">➕</span>
            新增商品
          </el-button>
          <el-button 
            v-else 
            class="action-btn primary-btn" 
            @click="handleCategoryAdd"
          >
            <span class="btn-icon">➕</span>
            新增分类
          </el-button>
        </div>
      </div>

      <!-- 主内容：Tabs -->
      <div class="content-wrapper">
        <el-card class="tabs-card">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="商品管理" name="product">
              <!-- 搜索筛选区域 -->
              <el-card class="filter-card">
                <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="商品名称">
              <el-input
                v-model="filterForm.keyword"
                placeholder="请输入商品名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item label="分类">
              <el-select
                v-model="filterForm.categoryId"
                placeholder="请选择分类"
                clearable
                style="width: 200px"
              >
                <el-option
                  v-for="cat in categories"
                  :key="cat.id"
                  :label="cat.categoryName"
                  :value="cat.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="filterForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 150px"
              >
                <el-option label="上架" :value="1" />
                <el-option label="下架" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
                </el-form>
              </el-card>

              <!-- 商品列表 -->
              <el-card class="table-card">
                <el-table
                  v-loading="loading"
                  :data="productList"
                  stripe
                  style="width: 100%"
                >
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column label="商品图片" width="100">
              <template #default="{ row }">
                <el-image
                  :src="getImageUrl(row.mainImage)"
                  style="width: 60px; height: 60px"
                  fit="cover"
                />
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" min-width="200" />
            <el-table-column prop="categoryName" label="分类" width="120" />
            <el-table-column prop="productCode" label="商品编码" width="120" />
            <el-table-column label="价格" width="100">
              <template #default="{ row }">
                <span style="color: #f56c6c">¥{{ row.price }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="stockQuantity" label="库存" width="80" />
            <el-table-column prop="salesCount" label="销量" width="80" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'info'">
                  {{ row.status === 1 ? '上架' : '下架' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="推荐" width="80">
              <template #default="{ row }">
                <el-tag :type="row.isFeatured === 1 ? 'warning' : ''">
                  {{ row.isFeatured === 1 ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button
                  link
                  :type="row.status === 1 ? 'warning' : 'success'"
                  size="small"
                  @click="handleToggleStatus(row)"
                >
                  {{ row.status === 1 ? '下架' : '上架' }}
                </el-button>
                <el-button
                  link
                  :type="row.isFeatured === 1 ? 'info' : 'warning'"
                  size="small"
                  @click="handleToggleFeatured(row)"
                >
                  {{ row.isFeatured === 1 ? '取消推荐' : '设为推荐' }}
                </el-button>
                <el-button link type="danger" size="small" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="pagination-wrapper">
                  <el-pagination
                    v-model:current-page="pagination.current"
                    v-model:page-size="pagination.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                  />
                </div>
              </el-card>
            </el-tab-pane>

            <el-tab-pane label="分类管理" name="category">
              <el-card>
                <el-table
                  v-loading="categoryLoading"
                  :data="categoryList"
                  stripe
                  row-key="id"
                  :tree-props="{ children: 'children' }"
                  default-expand-all
                  style="width: 100%"
                >
                  <el-table-column prop="categoryName" label="分类名称" min-width="200" />
                  <el-table-column prop="sortOrder" label="排序" width="100" />
                  <el-table-column label="状态" width="100">
                    <template #default="{ row }">
                      <el-tag :type="row.status === 1 ? 'success' : 'info'">
                        {{ row.status === 1 ? '启用' : '禁用' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
                  <el-table-column label="商品数量" width="100">
                    <template #default="{ row }">
                      <span>{{ row.productCount || 0 }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                      <el-button link type="primary" size="small" @click="handleCategoryEdit(row)">
                        编辑
                      </el-button>
                      <el-button link type="danger" size="small" @click="handleCategoryDelete(row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>

              <!-- 分类编辑对话框 -->
              <CategoryDialog
                v-model="categoryDialogVisible"
                :category-id="editingCategoryId"
                :parent-categories="categoryList"
                @success="handleCategoryDialogSuccess"
              />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </div>

    <!-- 商品编辑对话框 -->
    <ProductDialog
      v-model="dialogVisible"
      :product-id="editingProductId"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getProductList,
  deleteProduct,
  putOnShelf,
  pullOffShelf,
  setFeatured
} from '@/api/product'
import { getCategoryList, getCategoryTree, deleteCategory } from '@/api/category'
import ProductDialog from './components/ProductDialog.vue'
import CategoryDialog from '../Category/components/CategoryDialog.vue'
import { getImageUrl } from '@/utils/image'

const router = useRouter()
const userStore = useUserStore()

// 管理员信息
const adminName = computed(() => userStore.userInfo?.realName || '系统管理员')
const adminInitial = computed(() => adminName.value.charAt(0))

// 菜单列表
const menuList = [
  { name: 'dashboard', label: '数据看板', icon: '📊', path: '/admin/dashboard' },
  { name: 'employee', label: '员工管理', icon: '👥', path: '/admin/employee' },
  { name: 'card', label: '福利卡管理', icon: '🎁', path: '/admin/welfare-card' },
  { name: 'product', label: '商品管理', icon: '🛒', path: '/admin/product' },
  { name: 'order', label: '订单管理', icon: '📦', path: '/admin/order' },
  { name: 'statistics', label: '数据统计', icon: '📈', path: '/admin/statistics' }
]

// 菜单点击
const handleMenuClick = (menu) => {
  if (menu.path) {
    router.push(menu.path)
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
    ElMessage.error('退出登录失败')
  }
}

const activeTab = ref('product')
const loading = ref(false)
const productList = ref([])
const categories = ref([])
const total = ref(0)
const dialogVisible = ref(false)
const editingProductId = ref(null)

// 分类管理相关
const categoryLoading = ref(false)
const categoryList = ref([])
const categoryDialogVisible = ref(false)
const editingCategoryId = ref(null)

const filterForm = reactive({
  keyword: '',
  categoryId: null,
  status: null
})

const pagination = reactive({
  current: 1,
  size: 20
})

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      categories.value = res.data
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
  }
}

// 加载分类树（分类管理Tab）
const loadCategoryTree = async () => {
  categoryLoading.value = true
  try {
    const res = await getCategoryTree()
    if (res.code === 200 && res.data) {
      categoryList.value = res.data
    } else {
      ElMessage.error(res.message || '加载分类列表失败')
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
    ElMessage.error('加载分类列表失败')
  } finally {
    categoryLoading.value = false
  }
}

// 加载商品列表
const loadProducts = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      keyword: filterForm.keyword || undefined,
      categoryId: filterForm.categoryId || undefined,
      status: filterForm.status !== null ? filterForm.status : undefined
    }

    const res = await getProductList(params)
    if (res.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '加载商品列表失败')
    }
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadProducts()
}

// 重置
const handleReset = () => {
  filterForm.keyword = ''
  filterForm.categoryId = null
  filterForm.status = null
  pagination.current = 1
  loadProducts()
}

// 分类：新增/编辑/删除
const handleCategoryAdd = () => {
  editingCategoryId.value = null
  categoryDialogVisible.value = true
}

const handleCategoryEdit = (row) => {
  editingCategoryId.value = row.id
  categoryDialogVisible.value = true
}

const handleCategoryDelete = async (row) => {
  try {
    // 子分类与商品数量校验（前端提示）
    if (row.children && row.children.length > 0) {
      ElMessage.warning('该分类下还有子分类，无法删除')
      return
    }
    if (row.productCount && row.productCount > 0) {
      ElMessage.warning('该分类下还有商品，无法删除')
      return
    }

    await ElMessageBox.confirm(`确定要删除分类"${row.categoryName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteCategory(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadCategoryTree()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 新增
const handleAdd = () => {
  editingProductId.value = null
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  editingProductId.value = row.id
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除商品"${row.productName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await deleteProduct(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      loadProducts()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换上下架状态
const handleToggleStatus = async (row) => {
  try {
    const res = row.status === 1
      ? await pullOffShelf(row.id)
      : await putOnShelf(row.id)

    if (res.code === 200) {
      ElMessage.success('操作成功')
      loadProducts()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 切换推荐状态
const handleToggleFeatured = async (row) => {
  try {
    const res = await setFeatured(row.id, row.isFeatured === 0)
    if (res.code === 200) {
      ElMessage.success('操作成功')
      loadProducts()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadProducts()
}

// 页码改变
const handlePageChange = (page) => {
  pagination.current = page
  loadProducts()
}

// 对话框成功回调
const handleDialogSuccess = () => {
  dialogVisible.value = false
  loadProducts()
}

const handleCategoryDialogSuccess = () => {
  categoryDialogVisible.value = false
  loadCategoryTree()
}

// 初始化
onMounted(() => {
  loadCategories()
  loadProducts()
})

// 切换到分类管理时加载分类树
watch(activeTab, (val) => {
  if (val === 'category' && categoryList.value.length === 0) {
    loadCategoryTree()
  }
})
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.admin-product-page {
  display: flex;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 侧边栏 */
.sidebar {
  width: 220px;
  background-color: white;
  height: 100vh;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 100;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.admin-logo {
  display: flex;
  align-items: center;
}

.admin-logo-icon {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  box-shadow: 0 2px 8px rgba(255, 112, 67, 0.3);
}

.admin-logo-text {
  font-size: 18px;
  font-weight: 600;
  color: #ff5722;
}

.sidebar-menu {
  flex: 1;
  padding: 20px 0;
  overflow-y: auto;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  transition: all 0.3s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  &.active {
    background: linear-gradient(90deg, rgba(255, 112, 67, 0.08) 0%, rgba(255, 112, 67, 0.15) 100%);
    color: #ff5722;
    border-right: 3px solid #ff5722;
  }
}

.menu-icon {
  margin-right: 10px;
  width: 20px;
  text-align: center;
}

.sidebar-footer {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.admin-avatar-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.admin-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-weight: bold;
  margin-right: 10px;
  box-shadow: 0 2px 6px rgba(255, 112, 67, 0.3);
}

.admin-info {
  flex: 1;
}

.admin-name {
  font-weight: 500;
  font-size: 14px;
}

.admin-role {
  color: #909399;
  font-size: 12px;
}

/* 退出登录按钮 */
.logout-btn {
  width: 100%;
  background: linear-gradient(135deg, #ef5350 0%, #e53935 100%);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(239, 83, 80, 0.3);
}

.logout-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(239, 83, 80, 0.4);
}

.logout-icon {
  font-size: 14px;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  margin-left: 220px;
  padding: 20px;
}

/* 顶部导航 */
.top-nav {
  background-color: white;
  border-radius: 12px;
  padding: 15px 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  display: flex;
  align-items: center;
  margin: 0;
}

.page-title-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #ff7043 0%, #ff5722 100%);
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  color: white;
  box-shadow: 0 2px 8px rgba(255, 112, 67, 0.3);
}

.top-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  border: none;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  
  .btn-icon {
    font-size: 16px;
  }
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  &:active {
    transform: translateY(0);
  }
}

.primary-btn {
  background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%);
  color: white;
  
  &:hover {
    background: linear-gradient(135deg, #66b1ff 0%, #409EFF 100%);
  }
}

.content-wrapper {
  .tabs-card {
    margin-bottom: 20px;
  }

  .filter-card {
    margin-bottom: 20px;

    .filter-form {
      margin: 0;
    }
  }

  .table-card {
    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    width: 60px;
    
    .admin-logo-text,
    .menu-item span,
    .admin-info {
      display: none;
    }
  }
  
  .main-content {
    margin-left: 60px;
  }
  
  .top-nav {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .action-btn {
    padding: 8px 16px;
    font-size: 13px;
    
    .btn-icon {
      font-size: 13px;
    }
  }
}
</style>
